<template>
  <div class="customer-contribution">
    <el-card>
          <div class="select-item">
            <div class="class-columns">
              <div class="class-column">
                <span class="title-tag">{{$t('select.Geo')}}</span>
                <el-select v-model="geoValue" multiple collapse-tags style="margin-left: 5px;"
                           @change="changeGeo(geoValue)">
                  <el-option
                    v-for="item in geoData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div class="class-column">
                <span class="title-tag">{{$t('select.Region')}}</span>
                <el-select v-model="regionValue" multiple collapse-tags style="margin-left: 5px;"
                           @change="changeRegion(regionValue)" popper-class="font12px">
                  <el-option
                    v-for="item in regionData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div class="class-column">
                <span class="title-tag">{{$t('newSearchResult.country')}}</span>
                <el-select v-model="countryValue" multiple collapse-tags style="margin-left: 5px;"
                           @change="changeCountry(countryValue)">
                  <el-option
                    v-for="item in countryData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div  class="class-column">
                <span class="title-tag">{{$t('select.BG')}}</span>
                <el-select
                  v-model="bgValue"
                  multiple
                  collapse-tags
                  style="margin-left: 5px;"
                  @change="changeBg(bgValue)">
                  <el-option
                    v-for="item in bgData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div class="class-column">
                <span class="title-tag">{{$t('select.Segment')}}</span>
                <el-select v-model="segmentValue" multiple collapse-tags style="margin-left: 5px;"
                           @change="changeSegment(segmentValue)" popper-class="font12px">
                  <el-option
                    v-for="item in segmentData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </div>
          </div>
        </el-card>
    <div class="but-module">
      <el-button :class="{'active-btn': currentIndex === 1}" @click="toggleIndex(1)">{{$t('select.Lately')}}</el-button>
      <el-button :class="{'active-btn': currentIndex === 0}" @click="toggleIndex(0)">{{$t('select.History')}}</el-button>
    </div>
    <div class="content">
      <el-card>
        <el-row :gutter="20">
          <el-col :span="8">
            <div>
              <h3>{{$t('historical.CA')}}</h3>
              <div class="caEchart echart"></div>
            </div>
          </el-col>
          <el-col :span="8">
            <div>
              <h3>{{$t('historical.Rev')}}</h3>
              <div class="revEchart echart"></div>
            </div>
          </el-col>
          <el-col :span="8">
            <div>
              <h3>{{$t('historical.GP')}}</h3>
              <div class="gpEchart echart"></div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>

  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import {getUsername} from '../../utils/auth'
  export default {
    data() {
      return {
        geoData: [],
        geoValue: [],
        regionData: [],
        regionValue: [],
        countryData: [],
        countryValue: [],
        bgValue: [],
        bgData: [],
        segmentValue: [],
        segmentData: [],
        echartsObj: {
          caEchart: null,
          revEchart: null,
          gpEchart: null
        },
        echartsData: {
          caData: {},
          revData: {},
          gpData: {}
        },
        currentIndex: 1, // 1 现在；0是历史
        // revXData: [], // 特殊的rev横坐标；有问题有时候是undefined
      }
    },
    computed: {
      ...mapGetters(['sidebar'])
    },
    watch: {
      'sidebar.opened': function() {
        this.resizeChart()
      }
    },
    methods: {
      // 千分位处理
      comdify(n) {
        var re = /\d{1,3}(?=(\d{3})+$)/g;
        var n1 = n.replace(/^(\d+)((\.\d+)?)$/, function (s, s1, s2) {
          return s1.replace(re, '$&,') + s2
        })
        return n1
      },
      // selectMethods
      changeGeo() {
        this.regionValue = []
        this.countryValue = []
        this.changeGeoData()
        this.loadEcharts()
      },
      changeRegion() {
        this.countryValue = []
        this.changeRegionData()
        this.loadEcharts()
      },
      changeCountry() {
        this.loadEcharts()
      },
      changeBg() {
        this.loadEcharts()
      },
      changeSegment() {
        this.loadEcharts()
      },
      // showEchartMethods
      showCaEchart() {
        let _this = this
        let option = {
          // tooltip: {
            confine: true,
          //   trigger: 'axis',
          //   axisPointer: {
          //     type: 'cross',
          //     crossStyle: {
          //       color: '#999'
          //     }
          //   }
          // },
          tooltip: {
            confine: true,
            backgroundColor: 'rgba(255,255,255,1)',
            padding: [5, 10],
            textStyle: {
              color: '#7588E4'
            },
            extraCssText: 'box-shadow: 0 3px 12px rgba(224,226,233,1)',
            formatter: function (params) {
              if (params.seriesType === 'line') {
                let resultStr = params.seriesName + '<br />' + params.name + ': ' + params.data + '%'
                return resultStr
              } else if (params.seriesType === 'bar') {
                let resultStr = params.seriesName + '<br />' + params.name + ': ' + _this.comdify(`${params.data}`)
                return resultStr
              }
            }
          },
          legend: {
            data:['CA', 'Cumulative CA Rate'],
            bottom: 'bottom',
          },
          grid: {
            left: 30,
            right: 20,
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: this.echartsData.caData.xTitle,
              axisPointer: {
                type: 'shadow'
              },
              axisLabel: {
                interval: 0,
                rotate: -45,
                color: '#959eaf'
              },
              axisLine: {
                lineStyle: {
                  color: '#959eaf'
                }
              }
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: 'CA',
              // axisLabel: {
              //   formatter: '{value} ml'
              // },
              axisLine: {
                lineStyle: {
                  color: '#959eaf'
                }
              },
              axisLabel: {
                interval: 0,
                // rotate: 40,
                color: '#959eaf',
                fontSize: 12
              },
              splitLine: {
                show: false
              }
            },
            {
              type: 'value',
              name: 'Cumulative CA Rate',
              axisLine: {
                lineStyle: {
                  color: '#959eaf'
                }
              },
              axisLabel: {
                formatter: '{value} %',
                interval: 0,
                color: '#959eaf',
                fontSize: 12
              },
            }
          ],
          series: [
            {
              name:'CA',
              type:'bar',
              data: this.echartsData.caData.ca,
              itemStyle: {
                normal: {
                  color: '#009eff'
                }
              },
              barWidth: 15
            },
            {
              name:'Cumulative CA Rate',
              type:'line',
              yAxisIndex: 1,
              data: this.echartsData.caData.caPer.map(item => (item * 100).toFixed(2)),
              itemStyle: {
                normal: {
                  color: '#b6a2de'
                }
              }
            }
          ]
        }
        this.echartsObj.caEchart.setOption(option)
      },
      showRevEchart() {
        let _this = this
        let option = {
          tooltip: {
            confine: true,
            backgroundColor: 'rgba(255,255,255,1)',
            padding: [5, 10],
            textStyle: {
              color: '#7588E4'
            },
            extraCssText: 'box-shadow: 0 3px 12px rgba(224,226,233,1)',
            formatter: function (params) {
              if (params.seriesType === 'line') {
                let resultStr = params.seriesName + '<br />' + params.name + ': ' + params.data + '%'
                return resultStr
              } else if (params.seriesType === 'bar') {
                let resultStr = params.seriesName + '<br />' + params.name + ': ' + _this.comdify(`${params.data}`)
                return resultStr
              }
            }
          },
          legend: {
            data:['Rev', 'Cumulative Rev Rate'],
            bottom: 'bottom',
          },
          grid: {
            left: 30,
            right: 20,
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              // data: this.revXData,
              data: this.echartsData.caData.xTitle,
              axisPointer: {
                type: 'shadow'
              },
              axisLabel: {
                interval: 0,
                rotate: -45,
                color: '#959eaf'
              },
              axisLine: {
                lineStyle: {
                  color: '#959eaf'
                }
              }
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: 'Rev ($K)',
              // axisLabel: {
              //   formatter: '{value} ml'
              // },
              axisLine: {
                lineStyle: {
                  color: '#959eaf'
                }
              },
              axisLabel: {
                interval: 0,
                color: '#959eaf',
                fontSize: 12
              },
              splitLine: {
                show: false
              }
            },
            {
              type: 'value',
              name: 'Cumulative Rev Rate',
              // axisLabel: {
              //   formatter: '{value} °C'
              // },
              axisLine: {
                lineStyle: {
                  color: '#959eaf'
                }
              },
              axisLabel: {
                interval: 0,
                color: '#959eaf',
                fontSize: 12,
                formatter: '{value} %',
              },
            }
          ],
          series: [
            {
              name:'Rev',
              type:'bar',
              data: this.echartsData.revData.rev,
              itemStyle: {
                normal: {
                  color: '#009eff'
                }
              },
              barWidth: 15
            },
            {
              name:'Cumulative Rev Rate',
              type:'line',
              yAxisIndex: 1,
              data: this.echartsData.revData.revPer.map(item => (item * 100).toFixed(2)),
              itemStyle: {
                normal: {
                  color: '#b6a2de'
                }
              }
            }
          ]
        }
        this.echartsObj.revEchart.setOption(option)
      },
      showGpEchart() {
        let _this = this
        let option = {
          tooltip: {
            confine: true,
            backgroundColor: 'rgba(255,255,255,1)',
            padding: [5, 10],
            textStyle: {
              color: '#7588E4'
            },
            extraCssText: 'box-shadow: 0 3px 12px rgba(224,226,233,1)',
            formatter: function (params) {
              if (params.seriesType === 'line') {
                let resultStr = params.seriesName + '<br />' + params.name + ': ' + params.data + '%'
                return resultStr
              } else if (params.seriesType === 'bar') {
                let resultStr = params.seriesName + '<br />' + params.name + ': ' + _this.comdify(`${params.data}`)
                return resultStr
              }
            }
          },
          legend: {
            data:['GP', 'Cumulative GP Rate'],
            bottom: 'bottom',
          },
          xAxis: [
            {
              type: 'category',
              data: this.echartsData.gpData.xTitle,
              axisPointer: {
                type: 'shadow'
              },
              axisLabel: {
                interval: 0,
                rotate: -45,
                color: '#959eaf'
              },
              axisLine: {
                lineStyle: {
                  color: '#959eaf'
                }
              }
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: 'GP ($K)',
              // axisLabel: {
              //   formatter: '{value} ml'
              // },
              axisLine: {
                lineStyle: {
                  color: '#959eaf'
                }
              },
              axisLabel: {
                interval: 0,
                color: '#959eaf',
                fontSize: 12
              },
              splitLine: {
                show: false
              }
            },
            {
              type: 'value',
              name: 'Cumulative GP Rate',
              // axisLabel: {
              //   formatter: '{value} °C'
              // },
              axisLine: {
                lineStyle: {
                  color: '#959eaf'
                }
              },
              axisLabel: {
                interval: 0,
                color: '#959eaf',
                fontSize: 12,
                formatter: '{value} %',
              },
            }
          ],
          grid: {
            left: 30,
            right: 20,
            containLabel: true
          },
          series: [
            {
              name:'GP',
              type:'bar',
              data: this.echartsData.gpData.gp,
              itemStyle: {
                normal: {
                  color: '#009eff'
                }
              },
              barWidth: 15
            },
            {
              name:'Cumulative GP Rate',
              type:'line',
              yAxisIndex: 1,
              data: this.echartsData.gpData.gpPer.map(item => (item * 100).toFixed(2)),
              itemStyle: {
                normal: {
                  color: '#b6a2de'
                }
              }
            }
          ]
        }
        this.echartsObj.gpEchart.setOption(option)
      },
      resizeChart() {
        setTimeout(() => {
          this.echartsObj.caEchart.resize()
          this.echartsObj.revEchart.resize()
          this.echartsObj.gpEchart.resize()
        }, 200)
      },
      // axios&loadData
      async initGeo() {
        let params = {
          username: getUsername()
        }
        let res = await this.axios.post('dropSelect/geoSelect.do', params)
        let resData = res.data.data
        this.geoData = resData.geo.map(item => {
          return {
            value: item,
            label: item
          }
        })
      },
      async initRegion() {
        let params = {
          username: getUsername(),
          geos: this.geoValue
        }
        let res = await this.axios.post('dropSelect/regionSelect.do', params)
        let resData = res.data.data
        this.regionData = resData.region.map(item => {
          return {
            value: item,
            label: item
          }
        })
      },
      async initCountry() {
        let params = {
          username: getUsername(),
          geos: this.geoValue,
          regions: this.regionValue
        }
        let res = await this.axios.post('dropSelect/countrySelect.do', params)
        let resData = res.data.data
        this.countryData = resData.country.map(item => {
          return {
            value: item,
            label: item
          }
        })
      },
      async loadBg() {
        let params = {
          username: getUsername()
        }
        let res = await this.axios.post('dropSelect/bgSelect.do', params)
        let resData = res.data.data
        this.bgData = resData.map(item => {
          return {
            value: item,
            label: item
          }
        })
      },
      async loadSegment() {
        let params = {
          username: getUsername()
        }
        let res = await this.axios.post('dropSelect/segmentSelect.do', params)
        let resData = res.data.data
        this.segmentData = resData.map(item => {
          return {
            value: item,
            label: item
          }
        })
      },
      async changeGeoData() {
        let params = {
          username: getUsername(),
          geos: this.geoValue
        }
        let res = await this.axios.post('dropSelect/geoSelect.do', params)
        let resData = res.data.data
        console.log('______')
        console.log(resData)
        console.log(resData.region)
        if (resData.region) {
          this.regionData = resData.region.map(item => {
            return {
              value: item,
              label: item
            }
          })
          this.countryData = resData.country.map(item => {
            return {
              value: item,
              label: item
            }
          })
        } else {
          this.initRegion()
        }
      },
      async changeRegionData() {
        let params = {
          username: getUsername(),
          geos: this.geoValue,
          regions: this.regionValue
        }
        let res = await this.axios.post('dropSelect/regionSelect.do', params)
        let resData = res.data.data
        if (resData.country) {
          this.countryData = resData.country.map(item => {
            return {
              value: item,
              label: item
            }
          })
        } else {
          this.initCountry()
        }
      },

      async loadCaEchart() {
        let params = {
          geos: this.geoValue,
          regions: this.regionValue,
          countrys: this.countryValue,
          bgs: this.bgValue,
          segments: this.segmentValue,
          flag: this.currentIndex
        }
        let res = await this.axios.post('customerContribution/caChart', params)
        let resData = res.data.data
        this.echartsData.caData = resData
        this.showCaEchart()
      },
      async loadRevEchart() {
        let params = {
          geos: this.geoValue,
          regions: this.regionValue,
          countrys: this.countryValue,
          bgs: this.bgValue,
          segments: this.segmentValue,
          flag: this.currentIndex
        }
        let res = await this.axios.post('customerContribution/revChart', params)
        let resData = res.data.data
        this.echartsData.revData = resData
        setTimeout(() => {
          this.showRevEchart()
        }, 100)
      },
      async loadGpEchart() {
        let params = {
          geos: this.geoValue,
          regions: this.regionValue,
          countrys: this.countryValue,
          bgs: this.bgValue,
          segments: this.segmentValue,
          flag: this.currentIndex
        }
        let res = await this.axios.post('customerContribution/gpChart', params)
        let resData = res.data.data
        this.echartsData.gpData = resData
        this.showGpEchart()
      },
      loadEcharts() {
        this.loadCaEchart()
        this.loadRevEchart()
        this.loadGpEchart()
      },
      toggleIndex(index) {
        if (index === this.currentIndex) {
          return
        }
        this.currentIndex = index
        this.loadEcharts()
      }
    },
    created() {
      this.initGeo()
      this.initRegion()
      this.initCountry()
      this.loadBg()
      this.loadSegment()
      this.loadCaEchart()
      this.loadRevEchart()
      this.loadGpEchart()
    },
    mounted() {
      this.echartsObj.caEchart = this.echarts.init(document.getElementsByClassName('caEchart')[0])
      this.echartsObj.revEchart = this.echarts.init(document.getElementsByClassName('revEchart')[0])
      this.echartsObj.gpEchart = this.echarts.init(document.getElementsByClassName('gpEchart')[0])
      let _this = this
      window.onresize = function() {
        _this.resizeChart()
      }

      // // 要删除的
      // let allArr = [['1','2','3'], ['4','5','6'], ['3','2','1'], ['3','5','7']]
      // //排序
      // allArr = allArr.map(item => {
      //   return item.sort((a, b) => {
      //     return a - b
      //   })
      // })
      // // console.log(allArr)
      // let newArr = []
      // allArr.forEach(item => {
      //   newArr.push(item.join(''))
      // })
      // console.log(newArr)
      // let result = Array.from(new Set(newArr))
      // result = result.map(item => item.split(''))
      // console.log('结果')
      // console.log(result)

    }
  }
</script>

<style lang="scss" scoped>
  .customer-contribution {
    /*padding: 10px;*/
    padding: 20px 46px;
    .class-columns {
      display: -webkit-box;
      .class-column {
        margin-right:30px;
        .title-tag {
          font-size: 16px;
        }
        .selectName{
          font-size: 14px;
          color: #15122f;
        }
      }
    }
    .echart {
      width: 100%;
      height: 400px;
    }
    .but-module {
      margin-top: 20px;
      text-align: center;
      .el-button {
        color: #333;
        background-color: #fff;
        width: 144px;
      }
      .active-btn {
        background-color: #0090e9;
        color: #fff;
      }
    }
    .content {
      margin-top: 10px;
      h3{
        font-weight: 700;
        font-size: 16px;
        color: #666;
      }
    }
  }
</style>
